//
//  WatchCodeViewController.m
//  XinKaiFa55like
//
//  Created by 55like on 2017/9/23.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "WatchCodeViewController.h"
#import "LFImagePickerController.h"
#import <Photos/PHAssetChangeRequest.h>


@interface WatchCodeViewController ()<LFImagePickerControllerDelegate>

@property (nonatomic,strong)UIImageView * codeImage;

@property (nonatomic,strong)UIImage * image;

@property (nonatomic,copy)void(^block)(void);

@end

@implementation WatchCodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.block = self.otherInfo[@"block"];
    
    self.view.backgroundColor = rgb(57, 57, 57);
    
    [self rightButton:nil image:@"xkf_shareicon" sel:@selector(setImage)];
    
    self.navleftButton = [self leftButton:@"个人资料" image:@"headreturn" sel:@selector(backButtonClicked:)];
    [self updateButtonSatatus:self.navleftButton];
    
    
    UIView * bcview = [[UIView alloc]initWithFrame:CGRectMake(10, (kScreenHeight - 64 - 380)/2+64, kScreenWidth - 20, 380)];
    bcview.backgroundColor = [UIColor whiteColor];
    bcview.layer.cornerRadius = 5;
    bcview.clipsToBounds =  YES;
    [self.view addSubview:bcview];
    
    UIImageView * headerview = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
    [headerview imageWithURL:[self.userInfo valueForJSONStrKey:@"path"] useProgress:NO useActivity:NO];
    [bcview addSubview:headerview];
    
    
    UILabel * namelab = [RHMethods labelWithFrame:CGRectMake(XW(headerview) + 10, Y(headerview) + 12, [[self.userInfo valueForJSONStrKey:@"realname"] widthWithFont:14], 12) font:Font(14) color:rgbTxtDeepGray text:[self.userInfo valueForJSONStrKey:@"realname"]];
    [bcview addSubview:namelab];
    
    UIImageView * sexicon = [[UIImageView alloc]initWithFrame:CGRectMake(XW(namelab) + 8, Y(namelab), 11, 27/2)];
    if ([[self.userInfo valueForJSONStrKey:@"gender"] isEqualToString:@"女"]) {
        
        sexicon.image = [UIImage imageNamed:@"xkf_25nv"];
        
    }else{
        
        sexicon.image = [UIImage imageNamed:@"xkf_ntb"];
    }
    
    [bcview addSubview:sexicon];
    
    UILabel * addciss = [RHMethods labelWithFrame:CGRectMake(X(namelab), YH(namelab) + 10, bcview.frameWidth - XW(headerview) - 20, 12) font:Font(14) color:rgbTxtGray text:[NSString stringWithFormat:@"%@ %@",[self.userInfo valueForJSONStrKey:@"province"],[self.userInfo valueForJSONStrKey:@"city"]]];
    [bcview addSubview:addciss];
    
    
    self.codeImage = [[UIImageView alloc]initWithFrame:CGRectMake((bcview.frameWidth - 430/2)/2, YH(headerview) + 50, 430/2, 430/2)];
    [self.codeImage imageWithURL:[self.userInfo valueForJSONStrKey:@"wxicon"] defaultImage:@"xkf_wewm"];
    [bcview addSubview:self.codeImage];
    
    
    UILabel * title = [RHMethods labelWithFrame:CGRectMake(0, bcview.frameHeight - 15 - 10, bcview.frameWidth, 10) font:Font(14) color:rgbTxtDeepGray text:@"扫一扫上面的二维码图案，加我微信" textAlignment:NSTextAlignmentCenter];
    [bcview addSubview:title];
    
}
-(void)save{
    
    
    krequestParam
    NSMutableArray *fileData = [[NSMutableArray alloc] init];
    
    
    
    for (int i = 0; i < 1; i++) {
        
        UIImage *image = self.image;
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation([[Utility Share]imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)], 1),@"fileData",@"wxicon",@"fileKey",@"aa.jpg",@"fileName",@"image",@"fileType", nil];
        
        
        [fileData addObject:dic];
    }
    
    
    [NetEngine uploadAllFileAction:@"user/profiles" withParams:dictparam fileArray:fileData onCompletion:^(id resData, BOOL isCache) {
        
        
        [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
        
        
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            
            
            self.codeImage.image = self.image;
           
            
            if (self.block) {
                
                self.block();
            }
            
            
        }else{
            
            
            
            
            
            
            
        }
        
        
        
        
    } onError:^(NSError *error) {
        
        
        [SVProgressHUD showErrorWithStatus:@"请检查网络连接~"];
        
        
        
    } withMask:SVProgressHUDMaskTypeClear];
    
    
    
    
}
-(void)updateButtonSatatus:(UIButton *)btnT{
    CGSize imageSize = btnT.imageView.frame.size;
    CGSize titleSize = btnT.titleLabel.frame.size;
    CGSize textSize = [btnT.titleLabel sizeThatFits:CGSizeMake(MAXFLOAT, MAXFLOAT)];
    CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
    if (titleSize.width + 0.5 < frameSize.width) {
        titleSize.width = frameSize.width;
    }
    CGFloat totalHeight = (imageSize.height + titleSize.height + 2);
    btnT.imageEdgeInsets = UIEdgeInsetsMake((totalHeight - imageSize.height)/2, 10.0, (totalHeight - imageSize.height)/2, - titleSize.width);
    btnT.titleEdgeInsets = UIEdgeInsetsMake((totalHeight - imageSize.height)/2,  imageSize.width + 6, (totalHeight - imageSize.height)/2, 0);
}
-(void)setImage{
    
    
    EMWeakSelf(weakSelf);
    
   
    
    [QSheetQAlertView showQSheetQAlertViewWithTitleArray:@[@"保存图片",@"更换图片"] cellClickIndex:^(NSInteger index) {
        
        if (index == 0) {
            
            
            [weakSelf loadImageFinished:self.codeImage.image];
            
            
        }else{
            
            
            LFImagePickerController *imagePicker = [[LFImagePickerController alloc] initWithMaxImagesCount:10 delegate:weakSelf];
            imagePicker.allowTakePicture = NO;
            imagePicker.allowPickingVideo = NO;
            imagePicker.doneBtnTitleStr = @"完成";
            imagePicker.allowEditting = NO;
            imagePicker.allowPickingOriginalPhoto=YES;
            imagePicker.showRadioImage=YES;
            imagePicker.cropImageSize=CGSizeMake(kScreenWidth*1.5, kScreenWidth*1.5);
            
            [weakSelf presentViewController:imagePicker animated:YES completion:nil];
            
            
        }
        
        
        
        
    }];
    
    
    
}
#pragma mark LFImagePickerControllerDelegate

- (void)lf_imagePickerController:(LFImagePickerController *)picker didFinishPickingRadioCropImages:(UIImage *)cropImage originalImages:(UIImage *)originalImage{
    
    
    self.image = cropImage;
    
    [self save];
    
    
}
- (void)loadImageFinished:(UIImage *)image
{
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        
        //写入图片到相册
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
        
        
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        
        if (!error) {

            dispatch_async(dispatch_get_main_queue(), ^{
                
                [SVProgressHUD showImage:nil status:@"已保存到本地相册"];
            });
            
        }
        
        
        NSLog(@"success = %d, error = %@", success, error);
        
    }];
}


@end
